package zcj.stu.C42;

import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.*;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.ClassUtils;


public class C42 {
    public static void main(String[] args) {
        GenericApplicationContext context = new GenericApplicationContext();
        DefaultListableBeanFactory beanFactory = context.getDefaultListableBeanFactory();
        context.registerBean("config", Config.class);
        AnnotationConfigUtils.registerAnnotationConfigProcessors(beanFactory);
        context.refresh();
        //查看容器中的bean
        for (String beanDefinitionName : context.getBeanDefinitionNames()) {
            System.out.println(beanDefinitionName);
        }
    }

    @Configuration
    @Import(MyImportSelector.class)
    static class Config {
    }

    static class MyImportSelector implements DeferredImportSelector {//ImportSelector DeferredImportSelector 推迟导入配置类的加载

        @Override
        public String[] selectImports(AnnotationMetadata importingClassMetadata) {
            return new String[]{ExternConfig1.class.getName(), ExternConfig2.class.getName()};
        }
    }
    static class MyConditional1 implements Condition{
        @Override
        public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {

            return ClassUtils.isPresent("com.alibaba.druid.pool.DruidDataSource",null);
        }
    }
    static class MyConditional2 implements Condition{
        @Override
        public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
            return  !ClassUtils.isPresent("com.alibaba.druid.pool.DruidDataSource",null);
        }
    }
    @Configuration
    static class ExternConfig1 {
        @Bean
        @Conditional(MyConditional2.class)
        public MyDataSource1 myDataSource1 () {
            return new MyDataSource1 ();
        }
    }

    @Configuration
    static class ExternConfig2 {
        @Bean
        @Conditional(MyConditional1.class)
        public Bean2 bean2() {
            return new Bean2();
        }
    }

    static class MyDataSource1 {
    }
    static class Bean2 {
    }
}
